package com.rf.client.controller;

import com.rf.client.service.RegisterUserService;
import com.rf.common.response.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @Author rf
 * @Date 2022/4/17
 */
@RestController
@RequestMapping("/log")
@Slf4j
public class UserLoginController {

    @Autowired
    private RegisterUserService userService;

    /**
     * 身份认证
     */
    @PostMapping
    public ResponseVo logIn(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        // 封装成Token
        try {
            subject.login(new UsernamePasswordToken(username, password));
            return ResponseVo.SUCCESS("登录成功");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            log.error("用户名密码错误");
        }
        return ResponseVo.FAIL("认证失败");
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public ResponseVo logout() {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.logout();
            return ResponseVo.SUCCESS("退出成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseVo.FAIL("退出失败");
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseVo register(String username, String password) {
        return userService.register(username, password) ? ResponseVo.SUCCESS("注册成功") : ResponseVo.FAIL("注册失败");
    }


}
